//
//  TokenListViewController.m
//  Bees
//
//  Created by NowYouCanSee on 2019/3/4.
//  Copyright © 2019 xiaohan. All rights reserved.
//

#import "TokenListViewController.h"
#import "WallectService.h"
#import "XHSearchBar.h"


@interface  TokenListCell : XHBaseTableCell
@property (nonatomic,strong) UIImageView*logoImgV;
@property (nonatomic,strong) UILabel*titleLab;
@property (nonatomic,strong) UIButton *rightBtn;
@property (nonatomic,strong) NSIndexPath *indexPath;
@property (nonatomic,strong) UIView *line;

@property (nonatomic,copy) void(^AddBlock)(NSIndexPath*indexPath,BOOL add);
@end
@implementation TokenListCell
- (void)setupUI{
    self.logoImgV = [UIImageView new];
    [self.contentView addSubview:self.logoImgV];
    ViewBorderRadius(self.logoImgV, AdaptedWidth(13), 1, kLineColor);
    self.titleLab = [UILabel new];
    self.titleLab.textColor = UIColorHex(#000000);
    self.titleLab.font = kBoldFont(16);
    [self.contentView addSubview:self.titleLab];
    
    self.rightBtn = [UIButton new];
    [self.rightBtn setImage:IMAGE_NAMED(@"tokenAdd") forState:UIControlStateNormal];
    [self.rightBtn setImage:IMAGE_NAMED(@"corner_select_big") forState:UIControlStateSelected];
    [self.contentView addSubview:self.rightBtn];
    kWeakSelf(self);
    [self.rightBtn addTapBlock:^(UIButton * _Nonnull btn) {
        
        btn.selected = !btn.selected;
        !weakself.AddBlock?:weakself.AddBlock(weakself.indexPath,btn.selected);
    }];
    self.line = [UIView new];
    self.line.backgroundColor = kLineColor;
    [self.contentView addSubview:self.line];
}
- (void)layoutSubviews{
    [self.logoImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(AdaptedWidth(23));
        make.centerY.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(AdaptedWidth(26), AdaptedWidth(26)));
    }];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.logoImgV.mas_right).offset(AdaptedWidth(14));
        make.centerY.mas_equalTo(0);
    }];
    [self.rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(AdaptedWidth(35), AdaptedWidth(35)));
        make.right.mas_equalTo(AdaptedWidth(-16));
    }];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.bottom.mas_equalTo(0);
        make.height.mas_equalTo(CGFloatFromPixel(1));
    }];
}

@end

@interface TokenListViewController ()<UISearchBarDelegate>
@property (nonatomic,strong) WallectService*wallectService;
@property (nonatomic,strong) NSMutableArray*selCodes;
@end

@implementation TokenListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    self.selCodes = [NSMutableArray arrayWithArray:self.wallet.codes];
    [self.tableView.mj_header beginRefreshing];
}

- (void)loadMore:(BOOL)isMore{
    [self.wallectService getTokenListIsMore:isMore completion:^(BOOL success, BOOL isHaveNextPage, NSString * _Nonnull msg) {
        [self endHeaderFooterRefreshingIsHaveNextPage:isHaveNextPage];
        if (success) {
            [self.tableView reloadData];
        }else{
            [self.view makeToast:msg];
        }
    }];
}
- (void)setupUI{
    self.title = XLocalized(@"Tokens");
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIView*headV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    self.tableView.tableHeaderView = headV;
    XHSearchBar *searchBar = [[XHSearchBar alloc]initWithFrame:CGRectMake(kNormalSpace, 4, kScreenWidth-2*kNormalSpace, 36)];
    searchBar.placeholder = XLocalized(@"项目名称");
    [headV addSubview:searchBar];
    searchBar.delegate = self;
    self.tableView.rowHeight = AdaptedWidth(64);
}

#pragma mark - table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.wallectService.tokenList.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TokenListCell *cell = [TokenListCell cellForTableView:tableView];
    cell.indexPath = indexPath;
    TokenInfo *token = [self.wallectService.tokenList objectOrNilAtIndex:indexPath.row];
    [cell.logoImgV sd_setImageWithURL:String_To_URL(token.logo)];
    cell.titleLab.text = token.symbol;
    cell.rightBtn.selected = [self.selCodes containsObject:token.contract];
    cell.rightBtn.userInteractionEnabled = !([token.code isEqualToString:kContractName_BEESIOTOKEN] ||  [token.code isEqualToString:kContractName_EOSIOTOKEN]);
    kWeakSelf(self);
    cell.AddBlock = ^(NSIndexPath *indexPath,BOOL add) {
        [MBProgressHUD showLoadTitile:@"" ToView:weakself.view];
        TokenInfo *token = [weakself.wallectService.tokenList objectOrNilAtIndex:indexPath.row];
        if (add) {
            if ([weakself.selCodes containsObject:token.contract]) {
                return;
            }
            ///删除
            if ([weakself.wallet.deleteCodes containsObject:token.code]) {
                NSMutableArray *deleteCodes =weakself.wallet.deleteCodes.mutableCopy;
                [deleteCodes removeObject:token.code];
                weakself.wallet.deleteCodesJson = [deleteCodes modelToJSONString];
                [weakself.selCodes addObject:token.contract];
            }else{
                NSMutableArray*contracts = [NSMutableArray arrayWithArray:weakself.wallet.contracts];
                TokenInfo *addToken = [TokenInfo new];
                addToken.code = token.contract;
                addToken.symbol = token.symbol;
                addToken.modelId = token.modelId;
                addToken.logo = token.logo;
                if (![weakself.selCodes containsObject:addToken.code]) {
                    [weakself.selCodes addObject:addToken.code];
                    [contracts addObject:addToken];
                }
                ///记录添加的token
                weakself.wallet.contractsJson = [contracts modelToJSONString];
                ///记录添加token的合约
                weakself.wallet.codesJson = [weakself.selCodes modelToJSONString];
            }
        }else{
            if (![weakself.selCodes containsObject:token.contract]) {
                return;
            }
            NSMutableArray*contracts = [NSMutableArray arrayWithArray:weakself.wallet.contracts];
            [contracts enumerateObjectsUsingBlock:^(TokenInfo* obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.code isEqualToString:token.contract]) {
                    [contracts removeObject:obj];
                    [weakself.selCodes removeObject:token.code];
                }
            }];
            if (![weakself.wallet.deleteCodes containsObject:token.contract]) {
                NSMutableArray *deleteCodes =weakself.wallet.deleteCodes.mutableCopy;
                [deleteCodes addObject:token.contract];
                weakself.wallet.deleteCodesJson = [deleteCodes modelToJSONString];
                [weakself.selCodes removeObject:token.code];
            }
            ///记录添加的token
            weakself.wallet.contractsJson = [contracts modelToJSONString];
            ///记录添加token的合约
            weakself.wallet.codesJson = [weakself.selCodes modelToJSONString];
        }
        [[XHDataBaseManager shareInstance]updateWalletToDB:weakself.wallet];
        [MBProgressHUD hideHUDForView:weakself.view];
    };
    return cell;
}
#pragma mark - searchDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    DLog(@"searchText %@",searchText);
    self.wallectService.tokenKey = searchText;
    [self loadMore:NO];
}
#pragma mark - getter

- (WallectService*)wallectService{
    if (!_wallectService) {
        _wallectService = [WallectService new];
    }
    return _wallectService;
}

@end
